package com.eat.netty_server.hander;

import com.eat.netty_server.bean.ManageConnections;
import com.eat.netty_server.bean.Message;
import io.netty.buffer.ByteBuf;
import io.netty.buffer.Unpooled;
import io.netty.channel.ChannelHandlerContext;
import io.netty.channel.ChannelInboundHandlerAdapter;
import io.netty.util.CharsetUtil;

/**
 * @author CZF
 * @create 2022-03-29 15:44
 *
 *
 */

//自定义的ChannelInboundHandlerAdapter
public class InHander extends ChannelInboundHandlerAdapter {
    @Override
    public void channelActive(ChannelHandlerContext ctx) throws Exception {
        ManageConnections.channelList.put(1L,ctx.channel());
        System.out.println("客户端连接："+ctx.channel().remoteAddress());
        super.channelActive(ctx);
    }

    //读取客户端数据事件
    /*
    1. ChannelHandlerContext ctx:上下文对象, 含有 管道pipeline , 通道channel, 地址
    2. Object msg: 就是客户端发送的数据 默认Object
     */
    @Override
    public void channelRead(ChannelHandlerContext ctx, Object msg) throws Exception {
        Message message = (Message) msg;

        System.out.println("客户端发送的消息是："+message.getHead());
//        ctx.writeAndFlush("ok!");



    }

    //数据读取完毕
    @Override
    public void channelReadComplete(ChannelHandlerContext ctx) throws Exception {

        Message message = new Message();
        message.setHead(new byte[]{6,6,6,6});
        ctx.writeAndFlush(message);


    }

    //处理异常,一般是关闭通道
    @Override
    public void exceptionCaught(ChannelHandlerContext ctx, Throwable cause) throws Exception {
        System.out.println("异常是："+cause);
        System.out.println("服务端连接close!");
        ctx.close();

    }
}
